<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      img {
        height: 300px;
        width: 500px;
      }
    </style>
    <script>
      window.onload = function () {
        /**
         * 使图片可以自动切换
         */
        var img1 = document.getElementById("img1");
        var imgArr = [
          "./img/1.png",
          "./img/2.png",
          " ./img/3.png",
          "./img/4.png",
        ];
        var index = 0;
        var timer;
        var btn01 = document.getElementById("btn01");
        btn01.onclick = function () {
          /**
           * 开启定时器，自动切换图片
           */
          // 在开启定时器之前，需要上一个定时器关闭
          clearInterval(timer);
          timer = setInterval(function () {
            index++;

            //判断索引是否超过最大索引
            if (index >= imgArr.length) {
              index = 0;
            }
            img1.src = imgArr[index];
          }, 1000);
        };
        var btn02 = document.getElementById("btn02");
        btn02.onclick = function () {
          clearInterval(timer);
        };
      };
    </script>
  </head>
  <body>
    <img id="img1" src="./img/1.png" alt="" />
    <button id="btn01">开始</button>
    <button id="btn02">暂停</button>
  </body>
</html>
